package com.samnative.pineapple.main;

import android.Manifest;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.samnative.pineapple.entity.MyCodeModel;
import com.samnative.pineapple.entity.ShareData;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.utils.ViewHelper;
import com.makeramen.roundedimageview.RoundedImageView;
import com.shashank.sony.fancytoastlib.FancyToast;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 我的二维码
 */
public class MyCodeActivity extends BaseActivity implements OnClickListener, EasyPermissions.PermissionCallbacks {

    private ImageView share_iv;
    private RoundedImageView user_head_iv;
    private TextView code_tv;
    private FrameLayout fl_save;
    private RelativeLayout rl_center;
    /**
     * 分享的数据
     */
    private ShareData sd;
    private MyCodeModel model;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_code;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        findViewById(R.id.tv_back).setOnClickListener(this);
        share_iv = (ImageView) findViewById(R.id.share_iv);
        fl_save = find(R.id.fl_save);
        user_head_iv = find(R.id.user_head_iv);
        code_tv = find(R.id.code_tv);
        find(R.id.iv_share).setOnClickListener(this);
        find(R.id.tv_save_qrimg).setOnClickListener(this);
        rl_center = find(R.id.rl_center);
        ViewHelper.setHeight(mContext, rl_center, 1.32f);

        requestData();
    }


    /**
     * 请求数据
     */
    private void requestData() {
        // TODO Auto-generated method stub
        Map<String, String> map = new HashMap<String, String>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("_apiname", "user.index.push");

        HttpRequest.post(this, null, map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                model = GsonUtils.fromJson(result.toString(), MyCodeModel.class);
                Glide.with(mContext).load(model.getData().getUrl()).into(share_iv);
//                        address = model.getData().getAddress();
//                            JSONObject obj = new JSONObject(result)
//                                    .getJSONObject("data");
//                            share_iv
                code_tv.setText(model.getData().getMyCode());

                sd = new ShareData();
                sd.setTitle(model.getData().getContent());
                sd.setDescription(model.getData().getBottomContent());
                sd.setImage(model.getData().getUrl());
                sd.setUrl(model.getData().getAddress());

            }
        });
    }


    /**
     * 保存图片到系统相册并通知图库更新
     *
     * @param context
     * @param bmp
     */
    public static void saveImage(Context context, Bitmap bmp) {
        if (bmp == null) {
            FancyToast.showToast(context, "保存出错了", FancyToast.ERROR, true);
            return;
        }
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "fzt");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            FancyToast.showToast(context, "文件未发现", FancyToast.ERROR, false);
            e.printStackTrace();
        } catch (Exception e) {
            FancyToast.showToast(context, "保存出错了", FancyToast.ERROR, false);
            e.printStackTrace();
        }

        // 最后通知图库更新
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);

            file.delete();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
        FancyToast.showToast(context, "二维码保存成功", FancyToast.SUCCESS, true);

    }

    /**
     * 实现文本复制功能
     * add by wangqianzhou
     *
     * @param content
     */
    public static void copy(String content, Context context) {
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
        FancyToast.showToast(context, context.getString(R.string.capy_success), FancyToast.SUCCESS, false);

    }

    /**
     * 实现粘贴功能
     * add by wangqianzhou
     *
     * @param context
     * @return
     */
    public static String paste(Context context) {
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        return cmb.getText().toString().trim();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //requestCode=100为更新前请求的写入权限,用户许可后提示更新
        if (requestCode == 100) {
            fl_save.buildDrawingCache();
            Bitmap bit = fl_save.getDrawingCache();
            saveImage(mContext, bit);
        }

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        /**
         * 若是在权限弹窗中，用户勾选了'NEVER ASK AGAIN.'或者'不在提示'，且拒绝权限。
         * 这时候，需要跳转到设置界面去，让用户手动开启。
         */
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("权限请求")
                    .setRationale(getString(R.string.app_name) + "需要获取相关权限才能正常使用")
                    .build().show();
        }
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
//            case R.id.tv_copy_address:
//                copy(address, context);
//                break;
            case R.id.tv_save_qrimg:
                if (TextUtils.isEmpty(model.getCode())) {
                    return;
                }
                if (EasyPermissions.hasPermissions(MyCodeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    fl_save.buildDrawingCache();
                    Bitmap bit = fl_save.getDrawingCache();
                    saveImage(mContext, bit);
                } else {
                    EasyPermissions.requestPermissions(MyCodeActivity.this, "\"" + getString(R.string.app_name) + "\"需要获取相关权限才能正常使用,请确认",
                            100, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                break;
            case R.id.iv_share: {
                if (sd == null) {
                    break;
                }
                Intent intent = new Intent(mContext, ShareHelperActivity.class);
                intent.putExtra("shareData", sd);
                startActivity(intent, R.anim.act_enter_top_alpha, R.anim.act_enter_bottom_alpha);

            }
            default:
                break;
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
